// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 获取当前时间
    const now = new Date()
    // 设置清理时间阈值（30分钟）
    const threshold = new Date(now.getTime() - 30 * 60 * 1000)
    
    // 查找需要清理的房间
    const rooms = await db.collection('rooms').where({
      lastUpdateTime: _.lt(threshold),
      status: _.in(['waiting', 'finished'])
    }).get()
    
    if (rooms.data.length === 0) {
      return {
        success: true,
        message: '没有需要清理的房间'
      }
    }
    
    // 批量删除房间
    const deletePromises = rooms.data.map(room => {
      return db.collection('rooms').doc(room._id).remove()
    })
    
    await Promise.all(deletePromises)
    
    return {
      success: true,
      message: `成功清理 ${rooms.data.length} 个房间`
    }
  } catch (error) {
    console.error('清理房间失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 